package server;

import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class RequestProcessorrV extends Thread {
    private Socket socket;
    private String webappsPath;

    private Map<String,Map<String,Map<String,HttpServlet>>> hosts = new HashMap<>();

    public RequestProcessorrV(Socket socket, Map<String,Map<String,Map<String,HttpServlet>>> hosts,String webappsPath) {

        this.socket = socket;
        this.hosts = hosts;
        this.webappsPath = webappsPath;
    }

    @Override
    public void run() {
        try{

            InputStream inputStream = socket.getInputStream();
            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            Map<String,Map<String,HttpServlet>> contexts = hosts.get(request.getHost());//得到虚拟机的项目map

            if(contexts == null) {
                System.out.println("未找到虚拟机");
                response.outputHtml(webappsPath+"404");
                return;
            }
            String url = request.getUrl();
            String webName = url.split("/")[1];
            Map<String,HttpServlet> wrappers = contexts.get(webappsPath+System.getProperty("file.separator")
                    +webName);//得到对应项目的wrapper集
            if(wrappers == null) {
                System.out.println("未找到对应项目");
                response.outputHtml(webappsPath+"404");
                return;
            }
            HttpServlet httpServlet = wrappers.get(url.replace("/"+url.split("/")[1],""));


            // 静态资源处理
            if(httpServlet == null) {
                System.out.println("静态资源处理");
                response.outputHtml(webappsPath+request.getUrl());
            }else{
                // 动态资源servlet请求
                System.out.println("动态资源servlet请求");
                httpServlet.service(request,response);
            }
            socket.close();
        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
